package com.yang.sso.resource.handler;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.yang.common.core.result.R;

import java.io.IOException;

/**
 * @author zhouyang
 * @version v1.1
 * @date 2024/9/24 23:48
 * @description 拒绝访问拦截
 */
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        if(request.getUserPrincipal() instanceof AbstractOAuth2TokenAuthenticationToken){
            log.warn("权限不足.....");
            response.getWriter().write(JSONObject.toJSONString(new R<>(false,401,"权限不足")));
        }

        response.getWriter().flush();
    }
}
